/*
Author: 摘星fy
Editor: SublimeText
  Date: 2023-11-26 23:54:43
    QQ: 273259755
    WX: y273259755
*/

window.rand = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

window.clone = (o) => {
  return JSON.parse(JSON.stringify(o))
}

window.range = (min, max) => {
  const arr = Array(max - min + 1)
  for (let i = min; i <= max; i++) {
    arr[i - min] = i
  }
  return arr
}

window.sleep = (time) => {
  return time > 0 && new Promise((next) => {
    setTimeout(next, time)
  })
}

Array.prototype.forEachSync = async function(cb) {
  for (let i = 0, len = this.length; i < len; i++) {
    await cb(this[i], i, this)
  }
}

Array.prototype.mapSync = async function(cb) {
  const result = []
  for (let i = 0, len = this.length; i < len; i++) {
    result.push(await cb(this[i], i, this))
  }
  return result
}

Array.prototype.first = function() {
  return this[0]
}

Array.prototype.last = function() {
  return this[this.length - 1]
}

Array.prototype.remove = function(e) {
  for (let i = 0; i < this.length; i++) {
    if (this[i] === e) {
      this.splice(i, 1)
      i--
    }
  }
  return this
}

Array.prototype.fib = function(n = 0) {
  const result = Array(this.length)
  let t = 0
  for (let i = 0; i < this.length; i++) {
    result[i] = t
    t += this[i] + n
  }
  return result
}

Array.prototype.swap = function(a, b) {
  if (!(a >= 0 && a < this.length)) return
  if (!(b >= 0 && b < this.length)) return
  const t = this[a]
  this[a] = this[b]
  this[b] = t
}

Array.prototype.shuffle = function() {
  for (let i = this.length - 1; i > 0; i--) {
    this.swap(i, Math.floor(Math.random() * (i + 1)))
  }
  return this
}

Array.prototype.min = function() {
  if (!this.length) return 0
  return Math.min.apply(null, this)
}

Array.prototype.max = function() {
  if (!this.length) return 0
  return Math.max.apply(null, this)
}

Array.prototype.sum = function() {
  let t = 0
  for (let i = this.length - 1; i > -1; i--) {
    t += this[i]
  }
  return t
}

Date.prototype.format = function(format) {
  const o = {
    y: this.getFullYear(),
    m: this.getMonth() + 1,
    d: this.getDate(),
    h: this.getHours(),
    i: this.getMinutes(),
    s: this.getSeconds(),
  }

  return (format || 'y-m-d h:i:s').replace(/y|m|d|h|i|s/g, (k) => {
    const n = o[k]
    return n < 10 ? '0' + n : n
  })
}
